package com.lili.greedy;

/**
 * @Auther: 李 力
 * @Date: 2024/8/6
 * @Description: 零钱兑换问题
 * @version: 1.0
 */
public class Leetcode518 {
    /* 方法一:递归
     * 时间复杂度: O(coins.len^2)
     * 空间复杂度: O(1)
     * */
    public static int change(int amount, int[] coins) {
        return rec(0, coins, amount);
    }

    /*
     * index：当前硬币索引
     * coins: 硬币面值数组
     * remainder：剩余余额
     * */
    private static int rec(int index, int[] coins, int remainder) {
        /*
         * remainder=0，有解
         * remainder<0，无解
         * remainder>0，还需要继续递归
         * */
        if (remainder < 0) {
            return 0;
        } else if (remainder == 0) {
            return 1;//找到一个解
        } else {
            int count = 0;//解的个数
            for (int i = index; i < coins.length; i++) {
                int r = rec(i, coins, remainder - coins[i]);
                count = count + r;
            }
            return count;
        }
    }

    /*
     * 方法二：动态规划
     * 时间复杂度: O(amount*coins.len)
     * 空间复杂度: O(amount)
     * */
    public static int change2(int amount, int[] coins) {
        int[] dp = new int[amount + 1];
        dp[0] = 1;
        for (int coin : coins) {
            for (int i = coin; i <= amount; i++) {
                dp[i] = dp[i] + dp[i - coin];
            }
        }
        return dp[amount];
    }
}
